﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DatabaseComponent;
using System.Net.Mail;
using System.IO;


public partial class SubmitRequestEN : System.Web.UI.Page
{

    string strImage = "";


    public Ticket mobjTicket
    {
        get
        {
            if (ViewState["mobjTicket"] == null)
                ViewState["mobjTicket"] = System.Guid.NewGuid().ToString();
            return Session[ViewState["mobjTicket"].ToString()] as Ticket;
        }
        set
        {
            if (ViewState["mobjTicket"] == null)
                ViewState["mobjTicket"] = System.Guid.NewGuid().ToString();
            Session[ViewState["mobjTicket"].ToString()] = value;
        }
    }


    public Persons mobjPersons
    {
        get
        {
            if (ViewState["mobjPersons"] == null)
                ViewState["mobjPersons"] = System.Guid.NewGuid().ToString();

            return Session[ViewState["mobjPersons"].ToString()] as Persons;
        }
        set
        {
            if (ViewState["mobjPersons"] == null)
                ViewState["mobjPersons"] = System.Guid.NewGuid().ToString();

            Session[ViewState["mobjPersons"].ToString()] = value ;
        }
    }


    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            checkSecurityAndCustomizePage();
            bindTicketTypes();
        }
    }


    /// <summary>
    /// this function will bind TicketTypes to dropdownlist
    /// </summary>
    protected void bindTicketTypes()
    {
        TicketTypeDB objTicketTypeDB = new TicketTypeDB(ConnectionStrings.LMS);

        List<TicketType> lstTicketType = objTicketTypeDB.Select("", "");

        ddlRequestType.DataSource = lstTicketType;
        ddlRequestType.DataTextField = "TicketTypeNameEN";
        ddlRequestType.DataValueField = "ID";
        ddlRequestType.DataBind();


    }


    /// <summary>
    /// this function will check the security and customize the page
    /// </summary>
    private void checkSecurityAndCustomizePage()
    {
        mobjPersons = GlobalVars.getCurrentPerson();

        if (!mobjPersons.lstAllRulesIDs.Contains((long)RulesEnum.Ticket_add_page))
        {
            Response.Redirect("LoginEN.aspx");
        }
    }




    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            if (randomImageCtl1.isOk)
            {

                ReadAllControls();

                SaveRequest();
            }
            else
            {
                lblError.Text = "Please write characters in image exactly.";
                randomImageCtl1.clear();
            }
        }
    }


    /// <summary>
    /// this function will save the request data to the database
    /// </summary>
    private void SaveRequest()
    {
        TicketDB objTicketDB = new TicketDB(ConnectionStrings.LMS);

        objTicketDB.Insert(mobjTicket);
        
        if (mobjTicket.ID >= 0)
        {

            if (!strImage.Equals(string.Empty))
            {
                TicketImagesDB objTicketImagesDB = new TicketImagesDB(ConnectionStrings.LMS);
                TicketImages objTicketImages = new TicketImages();
                objTicketImages.TicketID = mobjTicket.ID;
                objTicketImages.TicketImage = strImage;
                objTicketImagesDB.Insert(objTicketImages);
            }

            SendRequestMail(mobjTicket);
            lblResult.Text = "Request submitted ok. " + "your Request ID is " + mobjTicket.ID.ToString();

            showHowToFollow(mobjTicket);

            clearAllControls();
        }
        else
        {
            lblError.Text = "Error submitting the request!";
        }
    }

    /// <summary>
    /// this function will show help to user to know what to do after sending ticket.
    /// </summary>
    /// <param name="mobjTicket">the ticket object</param>
    protected void showHowToFollow(Ticket mobjTicket)
    {
        Label lbBefore = new Label();
        lbBefore.Text = "Dear customer , We will dealing your request sent at the earliest possible time and you can follow your request from ";
        HyperLink hlSupport = new HyperLink();
        hlSupport.Text = "Support";
        hlSupport.Target = "_blank";
        hlSupport.NavigateUrl = "SupportMainEN.aspx";
        Label lbAfterSupport = new Label();
        lbAfterSupport.Text = " --> ";

        HyperLink hlSendedSupport = new HyperLink();

        hlSendedSupport.Text = "Change request actions";
        hlSendedSupport.NavigateUrl = "ChangeRequestEN.aspx";
        hlSendedSupport.Target = "_blank";
        Label lbAfterChange = new Label();
        lbAfterChange.Text = " --> ";

        HyperLink hlRequestDetails = new HyperLink();
        hlRequestDetails.Text = "Request No. " + mobjTicket.ID + " details";
        hlRequestDetails.Target = "_blank";
        hlRequestDetails.NavigateUrl = "EditRequestEN.aspx?ID=" + mobjTicket.ID;

        requestDetails.Controls.Add(lbBefore);
        requestDetails.Controls.Add(hlSupport);
        requestDetails.Controls.Add(lbAfterSupport);
        requestDetails.Controls.Add(hlSendedSupport);
        requestDetails.Controls.Add(lbAfterChange);
        requestDetails.Controls.Add(hlRequestDetails);
    }



    /// <summary>
    /// this function will send an email of the sended request
    /// </summary>
    /// <param name="tc">the ticket created by the request</param>
    private void SendRequestMail(Ticket tc)
    {
        
               

                string strTitle = "Submitted request";
                string strBody = "Thank you for submitting a support request in \"iLearn\" system.\r\nYour request ID is " + tc.ID.ToString();

                string MailAddress = mobjPersons.Email;

                

                GlobalVars.SendRequestMail(strTitle, GlobalVars.buildMailBody( strBody.Replace("\r\n","<br />"),false), MailAddress);
    }


    /// <summary>
    /// this function will clear all the controls
    /// </summary>
    private void clearAllControls()
    {
        txtTitle.Text = "";
        txtDetails.Text = "";
        mobjTicket = new Ticket();
        randomImageCtl1.clear();
        
    }

    /// <summary>
    /// this function will read all control values and set it to object
    /// </summary>
    protected void ReadAllControls()
    {
        if (mobjTicket == null)
        {
            mobjTicket = new Ticket();
            mobjTicket.StartTime = DateTime.Now;
        }
        mobjTicket.Details = txtDetails.Text;
        mobjTicket.EmployeeID = mobjPersons.GenID;
        mobjTicket.ModifyTime = DateTime.Now;
        mobjTicket.RequestTypeID = long.Parse(ddlRequestType.SelectedValue);
       
        mobjTicket.StatusID = 1;
        mobjTicket.Title = txtTitle.Text;


        if (flRequestImage.HasFile)
        {
            string strName = System.Guid.NewGuid().ToString();


            try
            {
                FileInfo fi = new FileInfo(flRequestImage.FileName);
                strName = strName + fi.Extension;
                flRequestImage.SaveAs(Server.MapPath("./TicketImages/" + strName));
                strImage = strName;
            }
            catch
            {
                strImage = "";
            }
        }

        
    }


}